<template>
  <div>
    <DynamicTable
      row-key="id"
      header-title="签到记录"
      :data-request="Api.check.recordPage"
      :columns="columns"
      bordered
      size="small"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import type { TableColumn } from '@/components/core/dynamic-table';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/';
  import Api from '@/api/';
  import { formatToDateTime } from '@/utils/dateUtil';

  defineOptions({
    name: 'CheckRecord',
  });

  interface TableListItem {
    id: number;
    studentId: number;
    courseId: number;
    checkType: number;
    checkTime: string;
    checkStatus: number;
    createTime: string;
  }

  const [DynamicTable, dynamicTableInstance] = useTable({
    pagination: {
      pageSize: 10,
      showSizeChanger: true,
      showQuickJumper: true,
    },
  });
  const [showModal] = useFormModal();

  const checkTypeMap = {
    1: '直接签到',
    2: '人脸签到',
    3: '二维码签到',
    4: '定位签到',
    5: '手势签到',
  };

  const checkStatusMap = {
    1: '正常',
    2: '迟到',
    3: '旷课',
    4: '请假',
  };

  const weekMap = {
    1: '星期一',
    2: '星期二',
    3: '星期三',
    4: '星期四',
    5: '星期五',
    6: '星期六',
    7: '星期天',
  };

  const studentList = ref([]);
  const courseList = ref([]);

  onMounted(async () => {
    const [studentData, courseData] = await Promise.all([
      Api.student.studentList({}),
      Api.student.courseList({}),
    ]);
    studentList.value = studentData;
    courseList.value = courseData;
  });

  const formSchemas = [
    {
      field: 'studentId',
      label: '学生',
      component: 'Select',
      required: true,
    },
    {
      field: 'courseId',
      label: '课程',
      component: 'Select',
      required: true,
      componentProps: {
        options: courseList,
        fieldNames: {
          label: 'courseName',
          value: 'id',
        },
      },
    },
    {
      field: 'checkType',
      label: '签到类型',
      component: 'Select',
      componentProps: {
        options: Object.entries(checkTypeMap).map(([value, label]) => ({
          value: Number(value),
          label,
        })),
      },
      required: true,
    },
    {
      field: 'createTime',
      label: '签到时间',
      component: 'DatePicker',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
      },
      required: true,
    },
    {
      field: 'checkStatus',
      label: '签到状态',
      component: 'Select',
      componentProps: {
        options: Object.entries(checkStatusMap).map(([value, label]) => ({
          value: Number(value),
          label,
        })),
      },
      required: true,
    },
  ];

  const openRecordModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}签到记录`,
        width: '50%',
        onFinish: async (values) => {
          if (record.id) {
            await Api.check.recordUpdate({ id: record.id }, values);
          } else {
            await Api.check.recordCreate(values);
          }
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: formSchemas,
      },
    });
    formRef?.setFieldsValue(record);
  };

  const delRowConfirm = async (record: TableListItem) => {
    await Api.check.recordDelete({ id: record.id });
    dynamicTableInstance?.reload();
  };

  const columns: TableColumn<TableListItem>[] = [
    {
      title: '记录ID',
      dataIndex: 'id',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '学生',
      dataIndex: 'userId',
      customRender: ({ text }) => {
        const student = studentList.value.find((item) => item.id === text);
        return student?.userName || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: studentList,
          fieldNames: {
            label: 'userName',
            value: 'id',
          },
        },
      },
    },
    {
      title: '课程',
      dataIndex: 'courseId',
      customRender: ({ text }) => {
        const course = courseList.value.find((item) => item.id === text);
        return course?.courseName || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: courseList,
          fieldNames: {
            label: 'courseName',
            value: 'id',
          },
        },
      },
    },
    {
      title: '时间',
      dataIndex: 'checkDate',
      formItemProps: {
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          showTime: false,
        },
      },
    },
    {
      title: '星期',
      dataIndex: 'weekDay',
      hideInSearch: true,
      customRender: ({ text }) => {
        return weekMap[text] || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: Object.entries(weekMap).map(([value, label]) => ({
            value: Number(value),
            label,
          })),
        },
      },
    },
    {
      title: '签到类型',
      dataIndex: 'checkType',
      customRender: ({ text }) => {
        return checkTypeMap[text] || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: Object.entries(checkTypeMap).map(([value, label]) => ({
            value: Number(value),
            label,
          })),
        },
      },
    },
    {
      title: '签到时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      customRender: ({ text }) => formatToDateTime(text),
    },
    {
      title: '签到状态',
      dataIndex: 'checkStatus',
      customRender: ({ text }) => {
        return checkStatusMap[text] || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: Object.entries(checkStatusMap).map(([value, label]) => ({
            value: Number(value),
            label,
          })),
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      hideInSearch: true,
      customRender: ({ text }) => formatToDateTime(text),
    },
    {
      title: '操作',
      width: 130,
      dataIndex: 'ACTION',
      hideInSearch: true,
      fixed: 'right',
      actions: ({ record }) => [
        {
          label: '删除',
          popConfirm: {
            title: '你确定要删除吗？',
            placement: 'left',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
</script>
